/**
 * Copyright @2016-present, Sumscope, Inc.
 * All rights reserved.
 */

const defaultsDeep = require('lodash/defaultsDeep');

const config = {
  server: {
    name: 'ss-koa',
    port: 3000
  },
  log: {
    level: 'info',
    filename: 'app'
  },
  redis: {
    ip: 'localhost',
    port: 6379,
    password: '',
    sentinel: {
      name: '',
      nodes: []
    }
  }
};

function processConfig() {
  let finalConfig = config;
  if (process.env.configPath) {
    const appOptions = require(process.env.configPath);
    finalConfig = defaultsDeep(appOptions, config);
  }
  let outerConfig = process.env.config === undefined ? {} : JSON.parse(process.env.config);
  if (outerConfig) {
    finalConfig = defaultsDeep(outerConfig, finalConfig);
    if (process.env.NODE_APP_INSTANCE) {
      finalConfig.server.port = parseInt(finalConfig.server.port) + parseInt(process.env.NODE_APP_INSTANCE);
    }
  }
  finalConfig.server.prefix = finalConfig.server.name;
  if (process.env.NODE_ENV === 'development') {
    finalConfig.server.prefix = finalConfig.server.prefix + ':' + require('os').hostname();
  }
  return finalConfig;
}

module.exports = processConfig();
